import 'dart:ui';

import 'package:flutter/material.dart';
//import 'package:flutter_native_image/flutter_native_image.dart';
import 'package:image_picker/image_picker.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:toast/toast.dart';
import 'dart:io';

class PapularinspectReult extends StatefulWidget {
  final Map param;
  PapularinspectReult(this.param);

  @override
  _MyHomePageState createState() => new _MyHomePageState(this.param);
}

class _MyHomePageState extends State<PapularinspectReult> {
  List formList;
  final Map param;
  bool select = false;

  _MyHomePageState(this.param);
  initState() {
    super.initState();
    formList = [
      {
        "title": '客户姓名',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '车牌号',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '车牌号',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '车牌号',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
    ];
  }

  photo(item) async {
    var image = await ImagePicker.pickImage(source: ImageSource.camera);
    if (image == null) return;
    //File _files = await FlutterNativeImage.compressImage(image.path);
    File _files = image;

    Map<String, String> map = new Map();

    HttpHelper.upLoadImage(_files, (data) {
      print('data');
      if (data.containsKey('code')) {
        Toast.show(data['msg'], context);
      } else {
        List tempimg1 =
            item.containsKey("urlArr1") ? item["urlArr1"] : new List();
        List tempimg = new List();
        tempimg.add(data["filename"]);
        tempimg.add(data["url"]);
        tempimg1.add(tempimg);
        setState(() {
          item["urlArr1"] = tempimg1;
        });
      }
    }, params: map);
  }

  Widget buildcontent() {
    List<Widget> tiles = [];
    Widget content;
    List postdata = param["post"];
    print(param);
    print('传递数值');
    for (var item in postdata) {
      print(item);
      if(item["show_report"].toString()=="1"){
        item["show_report"]="是";
      }else if(item["show_report"].toString()=="0"){
        item["show_report"]="否";
      }
      List<String> items = item["item"].split(',');
      Color value_color;
      if (item.containsKey("value") == false) {
        item["value"] = items[0];
      }
      if (item["value"] == items[0]) {
        value_color = Color.fromRGBO(25, 172, 249, 1);
      } else {
        value_color = Color.fromRGBO(203, 93, 86, 1);
      }
      TextEditingController textEditingController = TextEditingController();
      double height = 80;
      if (item["mustimg"] == "1") height = 270;
      tiles.add(Padding(
          padding: new EdgeInsets.fromLTRB(0, 1, 0, 0),
          child: Container(
            color: Colors.white,
            // height: height,
            child: new Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Padding(
                    padding: new EdgeInsets.fromLTRB(10, 12, 10, 0),
                    child: new Row(
                      children: <Widget>[
                        new Text(item["name"]),
                        item["mustimg"] == "1"
                            ? Padding(
                                padding: new EdgeInsets.fromLTRB(10, 0, 0, 0),
                                child: new GestureDetector(
                                    onTap: () {
                                      // photo(item);
                                    },
                                    child: new Image.asset(
                                      'resource/images/user/cremra.png',
                                      width: 20,
                                      height: 20,
                                      fit: BoxFit.contain,
                                    )))
                            : new Text(''),
                        Expanded(
                            child: Align(
                                child: Text(
                                  item["value"],
                                  style: TextStyle(color: value_color),
                                ),
                                alignment: Alignment.centerRight)),
                      ],
                    )),

                // item["item"] == ""
                //     ? new TextField(

                //         // controller: textEditingController,
                //         onChanged: (value) {
                //           print(value);
                //           setState(() {
                //             item['value'] = value;
                //           });
                //         },
                //         decoration: InputDecoration(
                //           hintText: item.containsKey("value")
                //               ? item['value']
                //               : '请填写相关信息',
                //           border: OutlineInputBorder(
                //             borderSide: BorderSide.none,
                //           ),
                //         ))
                //     : checkBox(item),
                checkBox(item),
                item.containsKey("numerical_value")
                    ? testresult(item)
                    : new Text(''),
                item.containsKey("urlArr1") ? imgs(item) : new Text('')
              ],
            ),
            // child: new Row(
            //   children: <Widget>[
            //     Expanded(
            //       child: new Padding(
            //           padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
            //           child: new Text(
            //             item['name'],
            //             style: TextStyle(
            //                 fontSize: 15,
            //                 color: Color.fromRGBO(102, 102, 102, 1)),
            //           )),
            //       flex: 1,
            //     ),
            //     new Padding(
            //         padding: new EdgeInsets.fromLTRB(0, 0, 10, 0),
            //         child: new Text(
            //           item['id'],
            //           style:
            //               TextStyle(fontSize: 15, color: Color.fromRGBO(27, 182, 251, 1)),
            //         )),
            //   ],
          )));
    }
    content = new Column(
        children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
        //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
        );
    return content;
  }

  //漆膜仪检测的数值
  Widget testresult(item) {
    Widget content;
    List<Widget> tiles = [];
    print(item["testnum"]);
    // int itemnum = int.parse(item["testnum"]);
    int itemnum = item['numerical_value'].length;
    for (var i = 0; i < itemnum; i++) {
      tiles.add(
        Padding(
          padding: new EdgeInsets.fromLTRB(10, 0, 0, 5),
          child: new Container(
            height: 30,
            width: 30,

            decoration: new BoxDecoration(
              border: new Border.all(color: Colors.red, width: 0.0), // 边色与边宽度
              color: Color(0xFF9E9E9E), // 底色
              //        borderRadius: new BorderRadius.circular((20.0)), // 圆角度
              borderRadius:
                  BorderRadius.all(Radius.circular(15.0)), // 也可控件一边圆角大小
            ),

            //color: Colors.red,
            child: new Align(
                alignment: Alignment.center,
                child: new Text(
                  item.containsKey('numerical_value')
                      ? item['numerical_value'][i].toString()
                      : '0',
                  style: TextStyle(color: Colors.white, fontSize: 10),
                )),
          ),
        ),
      );
    }
    content = new Wrap(spacing: 0, runSpacing: 0, children: tiles);
    return content;
  }

  Widget imgs(item) {
    List<Widget> tiles = [];
    Widget content;

    List items = item["urlArr1"];

    for (var i = 0; i < items.length; i++) {
      List temp1 = items[i] as List;
      tiles.add(Padding(
        padding: new EdgeInsets.fromLTRB(10, 10, 0, 10),
        child: GestureDetector(
            onTap: () {
              print('点击查看图片');
              Navigator.of(context).push(
                NinePicture(items, i),
              );
            },
            child: Image.network(temp1[1], width: 100, height: 100)),
      ));
    }
    content = new Wrap(spacing: 0, runSpacing: 0, children: tiles);
    //content = new Row(children: tiles);

    return content;
  }

  Widget checkBox(item) {
    List<Widget> tiles = [];
    Widget content;

    List<String> items = item["item"].split(',');

    String defaultv = items[0];
    if (select == false) {
      if (item.containsKey("value") == false) {
        item['value'] = defaultv;
      }
    } //设置选项默认值
    // for (var i = 0; i < items.length; i++) {
      tiles.add(Padding(
          padding: new EdgeInsets.fromLTRB(10, 17, 0, 0),
          child: Text('是否显示在报告中：',
              style: new TextStyle(
                  fontSize: 11, color: Color.fromRGBO(100, 100, 100, 1)))));
      tiles.add(Padding(
          padding: new EdgeInsets.fromLTRB(10, 0, 0, 0),
          child: SizedBox(
              width: 22,
              child: Radio<String>(
                  //当前Radio的值
                  hoverColor: Color.fromRGBO(200, 200, 200, 1),
                  focusColor: Color.fromRGBO(25, 172, 249, 1),
                  value: '是',
                  activeColor: Color.fromRGBO(25, 172, 249, 1),
                  groupValue: item['show_report'],
                  // groupValue: defaultv,
                  onChanged: (value) {
                    setState(() {
                      select = true;
                      // defaultv = value;
                      item['show_report'] = value;
                    });
                  }))));

      tiles.add(Padding(
          padding: new EdgeInsets.fromLTRB(10, 17, 0, 0),
          child: Text('是',
              style: new TextStyle(
                  fontSize: 11, color: Color.fromRGBO(100, 100, 100, 1)))));
                  tiles.add(Padding(
          padding: new EdgeInsets.fromLTRB(10, 0, 0, 0),
          child: SizedBox(
              width: 22,
              child: Radio<String>(
                  //当前Radio的值
                  hoverColor: Color.fromRGBO(200, 200, 200, 1),
                  focusColor: Color.fromRGBO(25, 172, 249, 1),
                  value: '否',
                  activeColor: Color.fromRGBO(25, 172, 249, 1),
                  groupValue: item['show_report'],
                  // groupValue: defaultv,
                  onChanged: (value) {
                    setState(() {
                      select = true;
                      // defaultv = value;
                      item['show_report'] = value;
                    });
                  }))));

      tiles.add(Padding(
          padding: new EdgeInsets.fromLTRB(10, 17, 0, 0),
          child: Text('否',
              style: new TextStyle(
                  fontSize: 11, color: Color.fromRGBO(100, 100, 100, 1)))));
    //}
    content = new Wrap(spacing: 0, runSpacing: 0, children: tiles);
    //content = new Row(children: tiles);

    return content;
  }

  Widget build(BuildContext context) {
    return
        // WillPopScope(
        //   child:
        new Scaffold(
      appBar: new AppBar(
        title: new Text(param["name"]),
        backgroundColor: Colors.white,
        iconTheme: new IconThemeData(color: Colors.black),
        elevation: 0,
        // backgroundColor: Color.fromRGBO(255, 204, 48, 1),
      ),
      body: new Center(
          child: Container(
              decoration: new BoxDecoration(
                color: Color.fromRGBO(238, 238, 238, 1),
              ),
              // child: Padding(
              //     padding: new EdgeInsets.fromLTRB(0, 15, 0, 0),
              //     child: new ListView(
              //       children: <Widget>[buildcontent()],
              //     )),
              child: Stack(
                children: <Widget>[
                  Align(
                    alignment: Alignment.topCenter,
                    child: Container(
                        color: Colors.white,
                        width: double.infinity,
                        height: param["mustmodel"] == "1" ? 300 : 0,
                        padding: new EdgeInsets.fromLTRB(0, 10, 0, 20),
                        //color: Colors.red,
                        //color: Colors.red,
                        child: Align(
                          alignment: Alignment.topCenter,
                          child: param["mustmodel"] == "1"
                              ? showProblem()
                              : new Text(""),
                        )),
                  ),
                  Align(
                      alignment: Alignment.bottomCenter,
                      child: Padding(
                        padding: new EdgeInsets.fromLTRB(
                            0, param["mustmodel"] == "1" ? 300 : 0, 0, 10),
                        child: new ListView(children: <Widget>[buildcontent()]),
                      )),
                ],
              ))),
      //onWillPop: () => willpop(),
    );
  }

  //异常图片
  Widget showProblem() {
    List<Widget> tiles = [];
    Widget content;
    List postData = param["post"];
    String modelUrl = "resource/images/jiance/carmodel2.png";
    if (postData[0]["post_id"] == "3043") {
      //结构件
      modelUrl = "resource/images/jiance/model/jiegou/jiegou.jpg";
    } else if (postData[0]["post_id"] == "3076") {
      //车身玻璃
      modelUrl = "resource/images/jiance/model/boli/boli.png";
    } else if (postData[0]["post_id"] == "3044") {
      //浸泡检测
      modelUrl = "resource/images/jiance/qinpao.png";
    }
    tiles.add(
      Positioned(
          child: new Image.asset(
        modelUrl,
        //fit:BoxFit.none
        //fit: BoxFit.fi,
      )),
    );

    // List postData = param["post"];
    for (var item in postData) {
      List<String> items = item["item"].split(',');

      var id = item["id"];
      print(id);
      if (item.containsKey("value")) {
        if (item["post_id"] == "3076") {
          String urls;
          for (int n = 0; n < items.length; n++) {
            if (item["value"] == items[n]) {
              if (n == 0) continue;
              //urls = 'resource/images/jiance/model/boli/40202.png';
              urls = 'resource/images/jiance/model/boli/' +
                  id.toString() +
                  '-' +
                  n.toString() +
                  '.png';
            }
          }
          if (item["value"] != items[0]) {
            File imgs = File(urls);
            var dir_bool = imgs.exists();
            print(dir_bool);
            print(urls);
            tiles.add(
              Positioned(child: new Image.asset(urls)),
            );
          }
        } else {
          if (items[0] != item["value"]) {
            String urls;
            if (item["post_id"] == "3043") {
              urls = 'resource/images/jiance/model/jiegou/' +
                  id.toString() +
                  '.png';
            } else
              urls = 'resource/images/jiance/model/qimian/' +
                  id.toString() +
                  '.png';
            File imgs = File(urls);
            var dir_bool = imgs.exists();
            print(dir_bool);
            print(urls);
            tiles.add(
              Positioned(
                  //     child: new Image.asset(
                  //   'resource/images/jiance/xlgx.png'
                  //   //fit:BoxFit.none
                  //   //fit: BoxFit.fi,
                  // )
                  child: new Image.asset(urls
                      //fit:BoxFit.none
                      //fit: BoxFit.fi,
                      )),
            );
          }
        }
      }
    }
    content = new Stack(children: tiles);
    return content;
  }

  Future<bool> willpop() {
    // _showDialog();
    Navigator.pop(context);
    return Future.value(false);
  }

  _showDialog() {
    showDialog<Null>(
      context: this.context,
      builder: (BuildContext context) {
        return new AlertDialog(
            title: Text('提示!'),
            content: new Text('此项是否已经检测完毕?'),
            actions: <Widget>[
              new FlatButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                    // Navigator.pop(context);
                  },
                  child: new Text('否，继续检测',
                      style: new TextStyle(color: Colors.red))),
              new FlatButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                    Navigator.pop(context);
                  },
                  child: new Text(
                    '是',
                    style: new TextStyle(color: Colors.black),
                  ))
            ]);
      },
    );
  }
}

class NinePicture<T> extends PopupRoute<T> {
  final String barrierLabel;
  final List picList;
  final int index;
  int startX;
  int endX;

  NinePicture(this.picList, this.index, {this.barrierLabel});

  @override
  Duration get transitionDuration => Duration(milliseconds: 2000);

  @override
  @override
  Color get barrierColor => Colors.black54;

  @override
  bool get barrierDismissible => true;

  AnimationController _animationController;

  @override
  AnimationController createAnimationController() {
    assert(_animationController == null);
    _animationController =
        BottomSheet.createAnimationController(navigator.overlay);
    return _animationController;
  }

  @override
  Widget buildPage(BuildContext context, Animation<double> animation,
      Animation<double> secondaryAnimation) {
    return MediaQuery.removePadding(
      removeTop: true,
      context: context,
      child: GestureDetector(
        child: AnimatedBuilder(
          animation: animation,
          builder: (BuildContext context, Widget child) => GestureDetector(
            onTap: () {
              Navigator.pop(context);
            },
            child: _PictureWidget(picList, index),
          ),
        ),
      ),
    );
  }
}

class _PictureWidget extends StatefulWidget {
  final List picList;
  final int index;

  _PictureWidget(this.picList, this.index);

  @override
  State createState() {
    return _PictureWidgetState();
  }
}

class _PictureWidgetState extends State<_PictureWidget> {
  int startX = 0;
  int endX = 0;
  int index = 0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    index = widget.index;
  }

  @override
  Widget build(BuildContext context) {
    return new Material(
      color: Colors.transparent,
      child: new Container(
        width: double.infinity,
        child: Stack(
          children: <Widget>[
            GestureDetector(
              child: Center(
                child: CachedNetworkImage(
                  imageUrl: widget.picList[index][1],
                  fit: BoxFit.cover,
                ),
              ),
              onHorizontalDragDown: (detail) {
                startX = detail.globalPosition.dx.toInt();
              },
              onHorizontalDragUpdate: (detail) {
                endX = detail.globalPosition.dx.toInt();
              },
              onHorizontalDragEnd: (detail) {
                _getIndex(endX - startX);
                setState(() {});
              },
              onHorizontalDragCancel: () {},
            ),
            Align(
              alignment: Alignment.bottomCenter,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: List.generate(
                  widget.picList.length,
                  (i) => GestureDetector(
                    child: CircleAvatar(
                      foregroundColor: Theme.of(context).primaryColor,
                      radius: 8.0,
                      backgroundColor: index == i
                          ? Theme.of(context).primaryColor
                          : Colors.white,
                    ),
                    onTap: () {
                      setState(() {
                        startX = endX = 0;
                        index = i;
                      });
                    },
                  ),
                ).toList(),
              ),
            )
          ],
        ),
        alignment: Alignment.center,
      ),
    );
  }

  void _getIndex(int delta) {
    if (delta > 50) {
      setState(() {
        index--;
        index = index.clamp(0, widget.picList.length - 1);
      });
    } else if (delta < 50) {
      setState(() {
        index++;
        index = index.clamp(0, widget.picList.length - 1);
      });
    }
  }
}
